package server;

import mapper.UserMapper;
import service.UserServiceImpl;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

//启用服务端口号接口
public class ServerOutPut implements Runnable{
    private int port;
    private volatile static boolean on = true;

    public int getPort() {
        return port;
    }

    public  void setOn(boolean on) {
        ServerOutPut.on = on;
    }

    public ServerOutPut(int port){
        this.port=port;
    }

    @Override
    public void run() {
        ServerSocket serverSocket=null;
        Socket socket=null;
        OutputStream outputStream=null;
        //while (on){
            try {
                serverSocket = new ServerSocket(port);
                //等待连接
                socket = serverSocket.accept();
                System.out.println("ServerOutput已连接："+socket.getInetAddress());
                while (on){
                    //System.out.println(on);
                    if(socket.isClosed()){
                        socket = serverSocket.accept();
                        System.out.println("ServerOutput已连接："+socket.getInetAddress());
                    }
                    //发送客户端信息
                    new ServerOutPutrun().run(socket,port);
                }
        } catch (IOException e) {
            System.out.println("OutPut端口被占用");
        }finally {
            try {
                outputStream.close();
            } catch (IOException e) {
               System.out.println("空对象2");
            }
            try {
                socket.close();
            } catch (IOException e) {
                System.out.println("空对象");
            }
            try {
                serverSocket.close();
            } catch (IOException e) {
                System.out.println("空对象");
            }
        }
        //}
    }
}
class ServerOutPutrun{
    public void run(Socket socket,int port){
        OutputStream outputStream = null;
        System.setProperty(String.valueOf(port),"");
        while (true){
            if("".equals(System.getProperty(String.valueOf(port)))){
                continue;
            }
            try {
                String message=System.getProperty(String.valueOf(port));
                //System.out.println("message=="+message);
                outputStream = socket.getOutputStream();
                outputStream.write(message.getBytes(StandardCharsets.UTF_8),0,message.getBytes(StandardCharsets.UTF_8).length);
                outputStream.close();
                break;
            } catch (IOException e) {
                e.printStackTrace();
               break;
            }
        }
    }
}
